import express from 'express';
import path from 'path';
import cookieParser from 'cookie-parser';
import logger from 'morgan';
// 设置控制台颜色的插件
import chalk from 'chalk';
// 解析http post提交的字段并且将他们复制给req.body中
import bodyParser from 'body-parser';
// 获取当前服务器的localIP
import { localAdress as localIp } from './common/_os_';
// 获取总路由
import { initRouter } from './routes/main';
//获取当前环境下的配置文件
const config = global.config = require('./config/' + process.env.NODE_ENV + '.js');
// 扩展字符串函数
import "./common/extend";
// 数据库
import DB from "./config/_db";
global._DB_ = new DB(config.DB);
// redis
import Redis from "./config/_redis";
global._Redis_ = new Redis(config.Redis);
// socket
import Socket from "./config/_socket";
global._Socket_ = new Socket(config.Socket);


const app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../public')));
// for parsing application/json 
app.use(bodyParser.json());
// for parsing application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// 指定模板路径
app.set("views", path.join(__dirname, '../views'));
app.set("view engine", "ejs");
// 注册路由
// app.use('/', indexRouter);
initRouter(app);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
//开启服务器
app.listen(config.port, () => {
  console.log(
    chalk.green(`Service start successfully！${new Date()}`)
  )
  console.log(
    chalk.green(`Local：http://127.0.0.1:${config.port}`)
  )
  console.log(
    chalk.green(`LAN：http://${localIp}:${config.port}`)
  )
})

app.use((err, req, res, next) => { //服务器出问题时调用，返回500并给出提示
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

